// $Id: util.c 100 2011-10-21 15:05:36Z cedric.shih@gmail.com $
/*
 * Copyright 2011 Cedric Shih (cedric dot shih at gmail dot com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <sys/time.h>
#include <errno.h>

#include "log.h"

#include "util.h"

int niohttp_timeval_diff(const struct timeval *t1,
		const struct timeval *t2, struct timeval *td)
{
	td->tv_sec = t2->tv_sec - t1->tv_sec;
	td->tv_usec = t2->tv_usec - t1->tv_usec;

	while (td->tv_usec < 0) {
		td->tv_usec += 1000000;
		td->tv_sec--;
	}

	if (td->tv_sec < 0) {
		niohttp_error("invalid timestamp");
		return EINVAL;
	}

	return 0;
}
